package com.ruoyi.quartz.task;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.bizsys.domain.AppUser;
import com.ruoyi.bizsys.domain.ExtMonnifyReservedAccounts;
import com.ruoyi.bizsys.domain.ExtTryQueue;
import com.ruoyi.bizsys.domain.RealNameAuth;
import com.ruoyi.bizsys.service.*;
import com.ruoyi.bizsys.utils.BizConstants;
import com.ruoyi.bizsys.vo.MonnifyReservedAccount;
import com.ruoyi.business.common.AsyncService;
import com.ruoyi.business.service.ICustVaService;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.utils.DictUtils;
import com.ruoyi.common.utils.Func;
import com.ruoyi.sms.domain.SmsSendData;
import com.ruoyi.system.service.ISysDictTypeService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.stream.Collectors;

/**
 * Monnify虚拟账号生成接口重试
 *
 * @author cyh
 */
@Slf4j
@AllArgsConstructor
@Component("monnifyExtApiRetry")
public class MonnifyExtApiRetry {

    private AsyncService asyncService;

    private IAppUserService appUserService;

    private IExtTryQueueService tryQueueService;

    private IRealNameAuthService realNameAuthService;

    private IExtMonnifyReservedAccountsService monnifyReservedAccountsService;

    private ICustVaService custVaService;

    @Autowired
    private ISysDictTypeService dictTypeService;

    public static final String MONNIFY_ACCOUNT_SUPPORT_BANK = "monnify_account_support_bank";

    public void run() {
        // 处理paystack虚拟账号相关接口重试
        custVaService.dealPaystackVaRetry();
        log.info("虚拟账号生成重试定时任务开始执行");
        List<ExtTryQueue> queues = tryQueueService.list(new QueryWrapper<ExtTryQueue>().eq("try_type", ExtTryQueue.VIRTUAL).eq("state", "0").le("try_count", 2));

        //需要区分定时任务及其他场景,设置线程Name.不修改池内的Name,New一个
        new Thread(() -> {
            queues.forEach(tryTask -> {
                QueryWrapper<ExtMonnifyReservedAccounts> queryWrapper = new QueryWrapper<ExtMonnifyReservedAccounts>()
                        .eq("cust_no", tryTask.getCustNo())
                        .eq("state", UserConstants.BUSINESS_NORMAL);
                int count = monnifyReservedAccountsService.count(queryWrapper);
                //生成虚拟账户接口
                if (count < getMonnifySuppertBanks().size()) {
                    reservedAccounts(tryTask);
                } else {
                    //已存在,结束
                    tryQueueService.transferSuccess(tryTask.getSerialNo(), tryTask.getCustNo());
                }
            });
            log.info("虚拟账号生成接口重试定时任务执行结束");
        }, Constants.CURRENT_NAME).start();

    }

    private void reservedAccounts(ExtTryQueue tryTask) {
        //不存在则重新
        try {
            custVaService.delCustVaForMonnify(tryTask.getCustNo());
            tryQueueService.transferSuccess(tryTask.getSerialNo(), tryTask.getCustNo());
        } catch (Exception e) {
            log.error("放款接口重试定时任务", e);
            //定时任务重试失败第一次才会发短信
            if (tryTask.getTryCount() == 0) {
                // sendSms(null, null, BizConstants.SMS_MONIFY_TRY_FAIL_SRY, tryTask.getUserId());
            }
        }
    }

    private void sendSms(String virtualAccount, String bankName, String smsTemplateType, String userId) {
        RealNameAuth realNameAuth = realNameAuthService.getOne(new QueryWrapper<RealNameAuth>().eq("user_id", userId));
        JSONObject param = new JSONObject();
        param.put("lastName", realNameAuth.getLastName());
        if (Func.isNotEmpty(virtualAccount)) {
            param.put("virtualAccount", virtualAccount);
        }

        if (Func.isNotEmpty(bankName)) {
            param.put("bankName", bankName);
        }

        AppUser appUser = appUserService.getOne(new QueryWrapper<AppUser>().eq("user_uuid", realNameAuth.getUserId()));
        SmsSendData smsData = SmsSendData.builder().noticeType(BizConstants.SMS_NOTICE_TYPE_NOTICE)
                .phoneNumber(appUser.getPhone()).countryCode(appUser.getCountryCode())
                .smsParam(param).smsType(smsTemplateType).build();
        asyncService.sendSms(smsData);
    }

    private List<String> getMonnifySuppertBanks() {
        List<SysDictData> monnifySuppertBanks = DictUtils.getDictCache(MONNIFY_ACCOUNT_SUPPORT_BANK);
        if (CollectionUtils.isEmpty(monnifySuppertBanks)) {
            monnifySuppertBanks = dictTypeService.selectDictDataByType(MONNIFY_ACCOUNT_SUPPORT_BANK);
            DictUtils.setDictCache(MONNIFY_ACCOUNT_SUPPORT_BANK, monnifySuppertBanks);
        }
        log.info("Monnify 虚拟账户支持银行：{}", monnifySuppertBanks);
        return monnifySuppertBanks.stream().map(SysDictData::getDictValue).collect(Collectors.toList());
    }

}

